import Vue from 'vue';
import axios from 'axios';

// 服务遍历器
const AjaxSend = {
  // 初始化
  init() {
    // axios 配置
    axios.defaults.timeout = 15000;
    // axios.defaults.baseURL = config.baseUrl;
    axios.defaults.baseURL = dataBaseUrl;
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    // 添加请求拦截器
    axios.defaults.withCredentials = false;// 不允许携带cookie
    axios.interceptors.request.use(config => {
      if (window.localStorage.access_token) {
        // config.headers.common.Authorization = 'Bearer' + ' ' + window.sessionStorage.getItem('authToken');
        config.headers.common.Authorization = localStorage.getExpire("token_type")+ ' ' +localStorage.getExpire("access_token");//配置默认权限
      }
      return config;
    }, error => {
      return Promise.reject(error);
    });
    // 添加响应拦截器
    axios.interceptors.response.use(response => {
      response.data = response.data;
      if (response.status !== 200) {
        return Promise.reject(response);
      }
      return response;
    }, error => {
      if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
        // 进行重新登陆
        localStorage.clear();
        top.location.href = loginPageUrl;
      }
      return Promise.reject(error);
    });
  },
  httpRequest: {
    url: ''
  },
  serviceApi: undefined,
  // 遍历所有服务接口
  loopServiceApi(serviceApi) {
    for (const i in serviceApi) {
      serviceApi[i].send = this.send;
    }
  },
  get(params, url) {
    return new Promise((resolve, reject) => {
      axios(url, {
        method: 'get',
        params
      }).then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      });
    });
  },
  post(params, url) {
    return new Promise((resolve, reject) => {
      axios(url, {
        method: 'post',
        data: params
      }).then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      });
    });
  },
  put(params, url) {
    return new Promise((resolve, reject) => {
      axios(url, {
        method: 'put',
        data: params
      }).then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      });
    });
  },
  delete(params, url) {
    return new Promise((resolve, reject) => {
      axios(url, {
        method: 'delete',
        data: params
      }).then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      });
    });
  },
  /* 为了解决cas拦截，所有的请求追加app后缀,请注意：get请求与其他类型请求追加app后缀的方式不一样 */
  send(params) {
    AjaxSend.serviceApi = this;
    // AjaxSend.httpRequest.url = AjaxSend.serviceApi.baseUrl + AjaxSend.serviceApi.requestUrl + '?';
    AjaxSend.httpRequest.url = AjaxSend.serviceApi.requestUrl + '?';
    const method = AjaxSend.serviceApi.method;
    const type = AjaxSend.serviceApi.type;
    /* 请求参数中数组参数必须转换 */
    if (params) {
      const reg = '\{\.*\}';
      const result = AjaxSend.httpRequest.url.match(reg);
      if (result) {
        for (const value of result) {
          let key = value.replace('{', '');
          key = key.replace('}', '');
          AjaxSend.httpRequest.url = AjaxSend.httpRequest.url.replace(value, params[key]);
        }
      }
      // 数组参数","转换拼接
      $.each(params, (key, value) => {
        if (value instanceof Array) {
          params[key] = value.join(",");
        }
      });
    } else {
      params = {};
    }

    if (method === 'post' || method === 'put' || method === 'delete') {
      if (type && type == 2) {
        AjaxSend.httpRequest.url += "1=1";
      } else {
        AjaxSend.httpRequest.url += $.param(params);
      }
    }
    try {
      if (method === 'get') {
        return AjaxSend.get(params, AjaxSend.httpRequest.url);
      } else if (method === 'post') {
        return AjaxSend.post(params, AjaxSend.httpRequest.url);
      } else if (method === 'put') {
        return AjaxSend.put(params, AjaxSend.httpRequest.url);
      } else if (method === 'delete') {
        return AjaxSend.delete(params, AjaxSend.httpRequest.url);
      }
    } catch (e) {
      return Promise.reject(e);
    }
  }
};
// 服务初始化
AjaxSend.init();
export default AjaxSend;
